const Users = require('../db/index').Users
const { uniqueObjArr } = require('../utils/index.js')

const getUserRouters = async (ctx) => {
  const { id } = ctx.request.query
  let doc = await Users.findOne({_id:id}).populate({
    path: 'roles',
    select: '-_id',
    populate: { 
      path: 'routerResources',
      select: '-_id',
    }
  })
  const userRouters = uniqueObjArr(doc.roles.reduce((pre,next)=>{
    return next.routerResources?next.routerResources:[]
  },[]))
  if (!doc) {
    ctx.body = {
        code: -1,
        msg: '用户名不存在'
    }
  }else{
    try {
      // await doc.save() // 更新mongo中对应用户名的token
      ctx.body = {
        code: 200,
        msg: 'success',
        userRouters:userRouters
      }
    } catch (err) {
      ctx.body = {
        code: -1,
        msg: '获取用户路由权限失败'
      }
    }
  }
}

const authFunc = {
  getUserRouters
};
module.exports = authFunc